<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Page;
class kucunController extends Controller
{

    function __construct()
    {
        parent::__construct();
        $this->check_auth(); //检查权限
        $zhangben = M("zhangben");
        $zhangben_array = $zhangben->where("school_id=".$_SESSION['school_id'])->select();
        $this->assign('zhangben_array',$zhangben_array);
        $zhangben = M("school");
        $zhangben_array = $zhangben->where("id=".$_SESSION['school_id'])->find();
       // var_dump($zhangben_array);
        $this->assign('school_info',$zhangben_array);

    }

    /**
     * 出库口，显示所有当前未出库的商品
     * 2019-6-16
     */
    public function showAll()
    {


        $stu_model = M('kucun');
        //导入分页助手类
        import('Org.Util.Page');

        //从账本中读取开始和结束时间
        $zhangben = M('zhangben');
        $_REQUEST['zhangben_id'] = isset($_REQUEST['zhangben_id']) ? $_REQUEST['zhangben_id'] : -1;
        $zmap['school_id'] = $_SESSION['school_id'];
        if ($_REQUEST['zhangben_id'] != -1) {
            $zmap['id'] = $_REQUEST['zhangben_id'];
        }
        $zhangben_last=$zhangben  ->where($zmap)->order("id Desc") ->find();
        $this->assign('student_number', $zhangben_last['student_number']);
        $begin_date = $zhangben_last['begin_date'];
        $end_date = $zhangben_last['end_date'];   //账本日期
//获取开始结束日期
        $begin_date= isset($_REQUEST['begin_date']) ? $_REQUEST['begin_date'] :$begin_date;
        $end_date= isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] :$end_date;
        //手动查询日期
        $map['date']=array('between',$begin_date.','.$end_date);
        $map['type'] = 1;
        $map['school_id'] =  $_SESSION['school_id'];
        $map['rest_number']  = array('gt',0);

        $total = $stu_model
            ->where($map)
            ->order("id ASC")
            ->count();
        $page_size = 100;
        $page = new Page($total, $page_size);
        $page->setConfig("header", '库存查询');
        $pageControl = $page->show();

       $stus =  $stu_model
                ->where($map)
                ->order("id ASC")
                ->limit($page->firstRow,$page->listRows)
               ->select();
    //   echo $stu_model->getLastSql();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
//
        $rest_total_show = 0;
        foreach ($stus as $k=>$v){
            if($v['guige']>0){
                $v['unit']=$v['guige_unit'];
                $v['price']=round($v['price']/$v['guige'],2);
             }
          //  $v['rest_total'] =round($v['rest_number'] * $v['price']);
            $v['rest_total'] = $v['total'];
            $rest_total_show += $v['rest_total'];
            $stus[$k] = $v;
        }
        $menu = M("menu");
        $menu_array = $menu->where("school_id=" . $_SESSION['school_id'])->select();
        $this->assign('menu_array', $menu_array);

        $djh = M("kucun");
        $danjuhao = $djh->field('danjuhao')
            ->where(array('type' => 2, "month" => date("Y-m"),"school_id"=> $_SESSION['school_id']))
            ->order('danjuhao desc')
            ->limit(1)
            ->find();
        $new_djh = intval($danjuhao['danjuhao']) + 1;
        $this->assign('danjuhao', $new_djh);
        $this->assign('stus', $stus);
        $this->assign('count', $total);
        $this->assign('date', date("Y-m-d"));
        $this->assign('page_title', "库存列表");
        $this->assign('rest_total_show', $rest_total_show);
        $this->assign('pageControl', $pageControl);
        $this->display();

    }

    /**
     * 出库动作
     */
    public function chuku()
    {
      //  var_dump($_REQUEST);
        $detail = $_REQUEST['detail'];
        $chuku = array();
        foreach ($detail as $k=>$v){
            if($v['ck_num']>0){
                //有效数据
                $chuku[] = $v;
            }
        }
        //$chuku 有效的出库数据
        $ck_log_array=array(
            'type' => 2,
            'opuser' => $_SESSION['username'],
            'school_id' => $_SESSION['school_id'],
            'total_money' => $_POST['ck_all_sum'],
            'datetime' => $_POST['date'],
            'memo' => json_encode($chuku),
            'month' => substr(trim($_POST['date']),0,7),
            'menu' => $_POST['caidan_menu'],
            'candj' => $_POST['can_avg']
        );
        $cklog = M('cklog');
        $logid=$cklog -> add($ck_log_array); //写入日志，返回日志ID
        $kucun=M('kucun'); //库存明细
        foreach ($chuku as $k => $v) {
           //写出库记录
            $out_single=array(
                "school_id" => $_SESSION['school_id'],
                "gid" => $v['gid'],
                "name" => $v['gname'],
                "price" => $v['price'],
                "out_number" => $v['ck_num'],
                "unit" => $v['unit'],
                "total" => $v['ck_total'],
                "shouhuoren" => $_POST['chukuren'],
                "sort" => $v['sort'],
                "danjuhao" =>$_POST['danjuhao'],
                "date" =>$_POST['date'],
                "month" =>substr(trim($_POST['date']),0,7),
                "type" => 2,
                "logid" => $logid,
                "orign_id" => $v['id'],
                "memo" => $_POST['memo']
            );
            $kucun ->add($out_single); //写入
            $kucun->where('id='.$v['id'])->setDec('rest_number',$v['ck_num']); // 剩余修改
        }

        $this->redirect('chukudan?logid='.$logid);//重定向到控制器的方法  display是本控制的方法

    }


    /**
     * 入库单
     */
    public function rukudan()
    {


        $stu_model = M('kucun');
        //导入分页助手类
        import('Org.Util.Page');

        //从账本中读取开始和结束时间
        $zhangben = M('zhangben');
        $_REQUEST['zhangben_id'] = isset($_REQUEST['zhangben_id']) ? $_REQUEST['zhangben_id'] : -1;
        if ($_REQUEST['zhangben_id'] != -1) {
            $zmap['id'] = $_REQUEST['zhangben_id'];
        }
        $logid= isset($_REQUEST['logid']) ? $_REQUEST['logid'] : 0;
        $zhangben_last=$zhangben  ->where($zmap)->order("id Desc") ->find();
        $begin_date = $zhangben_last['begin_date'];
        $end_date = $zhangben_last['end_date'];   //账本日期
//获取开始结束日期
        $begin_date= isset($_REQUEST['begin_date']) ? $_REQUEST['begin_date'] :$begin_date;
        $end_date= isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] :$end_date;
        //手动查询日期
        $map['date']=array('between',$begin_date.','.$end_date);
        if($logid){
            $map['logid'] = $logid;
            unset($map['date']);
        }

        $map['type'] = 1;
        $map['school_id'] =  $_SESSION['school_id'];
        $map['memo'] = array('neq','上期结转');
        $total = $stu_model
            ->where($map)
            ->order("id ASC")
            ->count();
        $page_size = 10;
        $page = new Page($total, $page_size);
        $page->setConfig("header", '入库单');
        $pageControl = $page->show();

        $stus =  $stu_model
                ->where($map)
                ->order("logid asc")
             //   ->limit($page->firstRow,$page->listRows)
               ->select();
      // echo $stu_model->getLastSql();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
//
        //定义处理后的数据
        $finally_array = array();
        $check_title = 0;
        $i = 0;
        $total = 0;
        $key_last = count($stus)-1;
        $j = 0;
        foreach ($stus as $k=>$v){

            if($check_title==0){
                //第一个首页
                $finally_array[$i]['check_title'] = 1; //标记第一页  新起一页
            }

            if($check_title!=$v['logid'] && $check_title!=0){
                //第2圈进来，如果和上一条记录是不是一天的 输出上次的记录
                $finally_array[$i]['name'] = '合计';
                $finally_array[$i]['total'] =number_format($total,2);
                $finally_array[$i]['check_title'] = 2; //标记结束页面
                $total = 0; //重新开始统计

                //写入新记录
                $i ++;  //插入新的汇总记录
                $j = 1;
                $finally_array[$i]['name'] = $v['name'];
                $finally_array[$i]['price'] = $v['price'];
                $finally_array[$i]['total'] = $v['total'];
                $finally_array[$i]['number'] = $v['number'];
                $finally_array[$i]['date'] = $v['date'];
                $finally_array[$i]['unit'] = $v['unit'];
                $finally_array[$i]['shouhuoren'] = $v['shouhuoren'];
                $finally_array[$i]['danjuhao'] = $v['danjuhao'];
                $finally_array[$i]['id'] = $j;
                $total += $v['total'];
                $finally_array[$i]['check_title'] = 1; //标记第一页
            }else{
                $j++;
                //第2圈进来，如果和上一条记录是同一天的  继续累加
                $total += $v['total'];
                $finally_array[$i]['id'] = $j;
                $finally_array[$i]['name'] = $v['name'];
                $finally_array[$i]['price'] = $v['price'];
                $finally_array[$i]['total'] = $v['total'];
                $finally_array[$i]['date'] = $v['date'];
                $finally_array[$i]['number'] = $v['number'];
                $finally_array[$i]['unit'] = $v['unit'];
                $finally_array[$i]['shouhuoren'] = $v['shouhuoren'];
                $finally_array[$i]['danjuhao'] = $v['danjuhao'];


            }

            //另起一页
            if ($k == $key_last){ //此为最后一次循环 生成汇总记录
                $i ++;  //插入新的汇总记录
              //  $total += $v['total'];
                $finally_array[$i]['name'] = '合计';
                $finally_array[$i]['total'] =1;
                $finally_array[$i]['total'] =number_format($total,2);
                $finally_array[$i]['date'] = $v['date'];
                $finally_array[$i]['check_title'] = 2; //标记第二页
              //  $finally_array[$i]['cxsign'] = 1; //标记第二页
                $cxruku_id = $v['logid']; //标记第二页
            }

            $i++;
            $check_title = $v['logid'];
        }
       //var_dump($finally_array);

        $this->assign('stus', $finally_array);
        $this->assign('cxruku_id', $cxruku_id);
        $this->assign('page_title', "入库单");
        $this->assign('pageControl', $pageControl);
        $this->display();

    }
    public function chukudan()
    {
        $stu_model = M('kucun');
        //导入分页助手类
        import('Org.Util.Page');
        //从账本中读取开始和结束时间
        $zhangben = M('zhangben');
        $_REQUEST['zhangben_id'] = isset($_REQUEST['zhangben_id']) ? $_REQUEST['zhangben_id'] : -1;
        if ($_REQUEST['zhangben_id'] != -1) {
            $zmap['id'] = $_REQUEST['zhangben_id'];
        }
        $logid= isset($_REQUEST['logid']) ? $_REQUEST['logid'] : 0;
        if($logid){
            $map['t.logid'] = $logid;
        }

        $zhangben_last=$zhangben  ->where($zmap)->order("id Desc") ->find();
        $begin_date = $zhangben_last['begin_date'];
        $end_date = $zhangben_last['end_date'];   //账本日期
//获取开始结束日期
        $begin_date= isset($_REQUEST['begin_date']) ? $_REQUEST['begin_date'] :$begin_date;
        $end_date= isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] :$end_date;
        //手动查询日期
        $map['t.date']=array('between',$begin_date.','.$end_date);
        $map['t.type'] = 2;
        $map['t.school_id'] =  $_SESSION['school_id'];
        $total = $stu_model
            ->alias('t')
            ->where($map)
            ->order("t.id ASC")
            ->count();
        $page_size = 10;
        $page = new Page($total, $page_size);
        $page->setConfig("header", '出库单');
        $pageControl = $page->show();

        $stus =  $stu_model
                 ->alias('t')
                 ->field('t.*,c.menu,c.total_money,c.candj')
                 ->join('left join ' . C('DB_PREFIX') . 'cklog as c on c.id = t.logid and c.type=t.type')
                 ->where($map)
                 ->order("t.logid asc")
             //   ->limit($page->firstRow,$page->listRows)
               ->select();
      // echo $stu_model->getLastSql();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
//
        //定义处理后的数据
        $finally_array = array();
        $check_title = 0;
        $i = 0;
        $total = 0;
        $key_last = count($stus)-1;
        $j = 0;
        foreach ($stus as $k=>$v){

            if($check_title==0){
                //第一个首页
                $finally_array[$i]['check_title'] = 1; //标记第一页  新起一页
            }

            if($check_title!=$v['logid'] && $check_title!=0){
                //第2圈进来，如果和上一条记录是不是一天的 输出上次的记录
                $finally_array[$i]['name'] = '合计';
                $finally_array[$i]['total'] =number_format($total,2);
                $finally_array[$i]['check_title'] = 2; //标记结束页面
                $total = 0; //重新开始统计

                //写入新记录
                $i ++;  //插入新的汇总记录
                $j = 1;
                $finally_array[$i]['name'] = $v['name'];
                $finally_array[$i]['price'] = $v['price'];
                $finally_array[$i]['total'] = $v['total'];
                $finally_array[$i]['number'] = $v['out_number'];
                $finally_array[$i]['date'] = $v['date'];
                $finally_array[$i]['unit'] = $v['unit'];
                $finally_array[$i]['shouhuoren'] = $v['shouhuoren'];
                $finally_array[$i]['danjuhao'] = $v['danjuhao'];
                $finally_array[$i]['menu'] = $v['menu'];
                $finally_array[$i]['candj'] = $v['candj'];
                $finally_array[$i]['id'] = $j;
                $total += $v['total'];
                $finally_array[$i]['check_title'] = 1; //标记第一页
            }else{
                $j++;
                //第2圈进来，如果和上一条记录是同一天的  继续累加
                $total += $v['total'];
                $finally_array[$i]['id'] = $j;
                $finally_array[$i]['name'] = $v['name'];
                $finally_array[$i]['price'] = $v['price'];
                $finally_array[$i]['total'] = $v['total'];
                $finally_array[$i]['date'] = $v['date'];
                $finally_array[$i]['number'] = $v['out_number'];
                $finally_array[$i]['unit'] = $v['unit'];
                $finally_array[$i]['shouhuoren'] = $v['shouhuoren'];
                $finally_array[$i]['danjuhao'] = $v['danjuhao'];
                $finally_array[$i]['menu'] = $v['menu'];
                $finally_array[$i]['candj'] = $v['candj'];


            }

            //另起一页
            if ($k == $key_last){ //此为最后一次循环 生成汇总记录
                $i ++;  //插入新的汇总记录
              //  $total += $v['total'];
                $finally_array[$i]['name'] = '合计';
                $finally_array[$i]['total'] =1;
                $finally_array[$i]['total'] =number_format($total,2);
                $finally_array[$i]['date'] = $v['date'];
                $finally_array[$i]['check_title'] = 2; //标记第二页
                $cxruku_id = $v['logid']; //标记第二页
            }

            $i++;
            $check_title = $v['logid'];
        }
       //var_dump($finally_array);

        $this->assign('stus', $finally_array);
        $this->assign('cxruku_id', $cxruku_id);
        $this->assign('page_title', "出库单");
        $this->assign('pageControl', $pageControl);
        $this->display();

    }

    public function cxruku()
    {
        $logid = $_REQUEST['cxruku_id'];
        $log_model = M('cklog');
        $map['ID'] = $logid;
        $map['school_id'] =  $_SESSION['school_id'];
        $log_info = $log_model->where($map)->find();

        if($log_info['type']!=1){
            $this->error('参数错误，本单并非是入库单，禁止进入！本次操作已经记录在案！请谨慎操作！');
        }
        $log_time = strtotime($log_info['datetime']);
        $count_time = time() - $log_time;

        if($count_time>259200){
            $this->error('入库订单超过三天，禁止撤销！本次操作已经记录在案！请谨慎操作！');
        }

        $kucun_model=M('kucun');
        $sql="SELECT * from think_kucun  where type=2 and orign_id in (select id from think_kucun b where type=1 and b.logid=".$logid.")";
        $kucun_info=$kucun_model->execute($sql);
        if($kucun_info>0){
            $this->error('入库商品已经产生出库，禁止撤销！本次操作已经记录在案！请谨慎操作！');
        }

        //执行撤销工作
        //撤销log
        $log_data=array("type"=>'-1');
        $res1=$log_model->where($map)->save($log_data);
        //撤销kucun
        $kucn_data = array("type" => '-1');
        $res2=$kucun_model->where("logid=".$logid)->save($kucn_data);
        if ($res1 && $res2) {
            $this->success('撤销成功！！');
         //   $this->redirect('rukudan');//重定向到控制器的方法  display是本控制的方法
        } else {
            $this->error('添加失败！！');
        }
    //  var_dump($log_info);

    }

    public function cxchuku()
    {
        $logid = $_REQUEST['cxruku_id'];
        $log_model = M('cklog');
        $map['ID'] = $logid;
        $map['school_id'] =  $_SESSION['school_id'];
        $log_info = $log_model->where($map)->find();

        if($log_info['type']!=2){
            $this->error('参数错误，本单并非是入库单，禁止进入！本次操作已经记录在案！请谨慎操作！');
        }
        $log_time = strtotime($log_info['datetime']);
        $count_time = time() - $log_time;

        if($count_time>259200){
            $this->error('出库订单超过三天，禁止撤销！本次操作已经记录在案！请谨慎操作！');
        }

        //出库归位
        $kucun_model=M('kucun');
        $kmap = array('type' => 2,"logid"=>$logid);
        $kucun_info=$kucun_model->where($kmap)->select();
        foreach ($kucun_info as $k=>$v){
            $kucun_model->where('ID='.$v['orign_id'])->setInc('rest_number',$v['out_number']); // 出库归位
        }

        //执行撤销工作
        //撤销log
        $log_data=array("type"=>'-2');
        $res1=$log_model->where($map)->save($log_data);
        //撤销kucun
        $kucn_data = array("type" => '-2');
        $res2=$kucun_model->where("logid=".$logid)->save($kucn_data);
        if ($res1 && $res2) {
            $this->success('撤销成功！！');
         //   $this->redirect('rukudan');//重定向到控制器的方法  display是本控制的方法
        } else {
            $this->error('添加失败！！');
        }
    //  var_dump($log_info);

    }



    public function rukuzhang()
    {


        $stu_model = M('kucun');
        //导入分页助手类
        import('Org.Util.Page');

        //从账本中读取开始和结束时间
        $zhangben = M('zhangben');
        $_REQUEST['zhangben_id'] = isset($_REQUEST['zhangben_id']) ? $_REQUEST['zhangben_id'] : -1;
        if ($_REQUEST['zhangben_id'] != -1) {
            $zmap['id'] = $_REQUEST['zhangben_id'];
        }
        $zhangben_last=$zhangben  ->where($zmap)->order("id Desc") ->find();
        $begin_date = $zhangben_last['begin_date'];
        $end_date = $zhangben_last['end_date'];   //账本日期
//获取开始结束日期
        $begin_date= isset($_REQUEST['begin_date']) ? $_REQUEST['begin_date'] :$begin_date;
        $end_date= isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] :$end_date;
        //手动查询日期
        $map['date']=array('between',$begin_date.','.$end_date);
        $map['type'] = 1;
        $map['memo'] = array('neq','上期结转');
        $map['school_id'] =  $_SESSION['school_id'];
        $total = $stu_model
            ->where($map)
            ->order("id ASC")
            ->count();
        $page_size = 17;  //流水账每页显示多少条以便打印
        $page = new Page($total, $page_size);
        $page->setConfig("header", '入库流水账');
        $pageControl = $page->show();

        $stus =  $stu_model
                ->where($map)
                ->order("logid asc")
             //   ->limit($page->firstRow,$page->listRows)
               ->select();
      // echo $stu_model->getLastSql();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
//
        //定义处理后的数据
        $finally_array = array();
        $last_date = 0;
        $last_danjuhao = 0;

        $total = 0;
        foreach ($stus as $k=>$v){
            $last_date1 = $v['date'];
            $last_danjuhao1 = $v['danjuhao'];


            if($v['danjuhao']!=$last_danjuhao && $last_date!=0){

            }elseif($v['date']==$last_date && $last_date!=0){
                $v['date'] = "";
            }


            if($v['danjuhao']==$last_danjuhao && $last_danjuhao!=0){
                $v['danjuhao'] = "";
            }


            $total += $v['total'];
            $v['jiecun'] = number_format($total,2);

            $last_date = $last_date1;
            $last_danjuhao = $last_danjuhao1;


            if(($k+1)%$page_size==0){
                $v['fenye'] = 1;
            }else{
                $v['fenye'] = 0;
            }

            $stus[$k] = $v;
        }
        $this->assign('stus', $stus);
        $this->assign('page_title', "入库流水账");
        $this->assign('pageControl', $pageControl);
        $this->display();

    }
    public function chukuzhang()
    {


        $stu_model = M('kucun');
        //导入分页助手类
        import('Org.Util.Page');
         $map['type'] = array("in",array(1,2));  //定义类别
        //从账本中读取开始和结束时间
        $zhangben = M('zhangben');
        $_REQUEST['zhangben_id'] = isset($_REQUEST['zhangben_id']) ? $_REQUEST['zhangben_id'] : -1;
        $_REQUEST['gid'] = isset($_REQUEST['gid']) ? $_REQUEST['gid'] : 0;
        if ($_REQUEST['zhangben_id'] != -1) {
            $zmap['id'] = $_REQUEST['zhangben_id'];
        }
        $zhangben_last=$zhangben  ->where($zmap)->order("id Desc") ->find();
        $begin_date = $zhangben_last['begin_date'];
        $end_date = $zhangben_last['end_date'];   //账本日期
//获取开始结束日期
        $_REQUEST['begin_date']= isset($_REQUEST['begin_date']) ? $_REQUEST['begin_date'] :$begin_date;
        $_REQUEST['end_date']= isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] :$end_date;

        //手动查询日期
        $map['date']=array('between',$_REQUEST['begin_date'].','.$_REQUEST['end_date']);
        if($_REQUEST['gid']){
            $map['gid'] = $_REQUEST['gid'];
        }
        //$map['type'] = 2;
        $map['school_id'] =  $_SESSION['school_id'];

        $total = $stu_model
            ->where($map)
            ->order("id ASC")
            ->count();
        $page_size = 17;  //流水账每页显示多少条以便打印
        $page = new Page($total, $page_size);
        $page->setConfig("header", '分类出库账');
        $pageControl = $page->show();

        $stus =  $stu_model
                ->where($map)
                ->order("gid asc,date asc")
             //   ->limit($page->firstRow,$page->listRows)
               ->select();
      // echo $stu_model->getLastSql();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
//
        //定义处理后的数据
        $last_gid = 0;
        $total = 0;
        $ci = 0;
        foreach ($stus as $k=>$v){

            if ($last_gid != 0) {
                if($last_gid==$v['gid']){
                    $ci++;
                    //无表头，不分页
                    if($ci%$page_size==0){
                        //有表头，头前分页
                        $v['title'] = 1;  //纯表头
                        $v['fenye'] = 1;  //纯分页
                    }else{
                        //无表头，不分页
                        $v['title'] = 0;  //纯表头
                        $v['fenye'] = 0;  //纯分页
                    }
                }else{
                    $total = 0;//换商品了，统计归零
                    $ci = 0;
                    //有表头，头前分页
                    $v['title'] = 1;  //纯表头
                    $v['fenye'] = 1;  //纯分页
                }
            }else{
                //纯表头
                $v['title'] = 1;  //纯表头
                $v['fenye'] = 0;  //不分页
            }

            //继续往下记
                //入账
               if($v['type']==1){
                   //入库
                   $total = $total + $v['total'];
                   $v['show_total'] = number_format($total,2);
                   $v['style'] = '入';
                   $v['r_price'] = $v['price'];
                   $v['r_total'] = '￥'.$v['total'];
                   $v['r_unit'] = $v['unit'];
               }
               //出账
                if($v['type']==2){
                    //入库
                    $total = $total - $v['total'];
                    $v['show_total'] = number_format($total,2);
                    $v['style'] = '出';
                    $v['c_price'] = $v['price'];
                    $v['c_total'] = '￥'.$v['total'];
                    $v['c_unit'] = $v['unit'];
                }

            unset($v['price']);
            unset($v['total']);
            unset($v['unit']);
            $last_gid = $v['gid']; //当前的菜ID
            $stus[$k] = $v;
          //  var_dump($v);
           // echo "<br>";
        }
        $Goods = M("goods");
        $goods_array = $Goods->where("school_id=" . $_SESSION['school_id'])->select();

        $this->assign('stus', $stus);
        $this->assign('goods_array', $goods_array);
        $this->assign('page_title', "出库分类账");
        $this->assign('pageControl', $pageControl);
        $this->display();

    }

    public function rukutotal()
    {


        $stu_model = M('cklog');
        //导入分页助手类
        import('Org.Util.Page');

        //从账本中读取开始和结束时间
        $zhangben = M('zhangben');
        $_REQUEST['zhangben_id'] = isset($_REQUEST['zhangben_id']) ? $_REQUEST['zhangben_id'] : -1;
        if ($_REQUEST['zhangben_id'] != -1) {
            $zmap['id'] = $_REQUEST['zhangben_id'];
        }
        $zhangben_last=$zhangben  ->where($zmap)->order("id Desc") ->find();
        $begin_date = $zhangben_last['begin_date'];
        $end_date = $zhangben_last['end_date'];   //账本日期
//获取开始结束日期
        $begin_date= isset($_REQUEST['begin_date']) ? $_REQUEST['begin_date'] :$begin_date;
        $end_date= isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] :$end_date;
        //手动查询日期
        $map['datetime']=array('between',$begin_date.','.$end_date);
        $map['type'] = 1;
        $map['school_id'] =  $_SESSION['school_id'];
        $map['isbuy'] = array('neq',1);
        $total = $stu_model
            ->where($map)
            ->order("sort ASC")
            ->count();
        $page_size = 20;  //流水账每页显示多少条以便打印
        $page = new Page($total, $page_size);
        $page->setConfig("header", '入库汇总');
        $pageControl = $page->show();

        $stus =  $stu_model
                ->field('id,type,total_money,sort,datetime,month')
                ->where($map)
                ->order("sort asc,datetime asc")
             //   ->limit($page->firstRow,$page->listRows)
               ->select();
     // echo $stu_model->getLastSql();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
//
        //定义处理后的数据
        $finally_array = array();
        $last_date = 0;

        $last_month = 0;
        $last_sort = "";

        $total_sort = 0;
        $total_month = 0;
        $total_all = 0;
        $i = 0;
        $key_last = count($stus)-1;

        foreach ($stus as $k=>$v){
            $v['datetime'] = substr($v['datetime'], 0, 10);

            if($v['sort']==$last_sort && $last_sort!=""){
                                //第二次进来
                //月份是否相同
                 if($v['month']==$last_month) {  //相同的话继续累加
                     $total_sort += $v['total_money'];
                     $total_month += $v['total_money'];
                     $finally_array[$i]['sort'] = $v['sort'];  //第一行输出类别
                     $finally_array[$i]['date'] = $v['datetime'];  //第一行输出日期
                     $finally_array[$i]['month'] = $v['month'];  //第一行输出月份
                     $finally_array[$i]['total'] = $v['total_money'];  //第一行输出价格

                     //另起一页
                     if ($k == $key_last) { //此为最后一次循环 生成汇总记录
                         $i++;  //插入新的汇总记录
                         //  $total += $v['total'];
                         $finally_array[$i]['month'] = $v['month'] . '汇总';
                         $finally_array[$i]['class'] = 1;  //CSS控制器
                         $finally_array[$i]['total'] = number_format($total_month,2);  //汇总
                         $total_all += $total_sort; //汇总总记录
                     }


                 }else{  //月份不同的话
                     //生成一条记录
                     $finally_array[$i]['sort'] = "";  //第一行输出类别
                     $finally_array[$i]['date'] = "";  //第一行输出日期
                     $finally_array[$i]['month'] = $last_month."汇总";  //第一行输出月份
                     $finally_array[$i]['class'] = 1;  //CSS控制器
                     $finally_array[$i]['total'] = number_format($total_month,2);  //汇总记录结束
                     $total_month = 0;//归零重计
                     $i++;
                     $finally_array[$i]['sort'] = "";  //第一行输出类别
                     $finally_array[$i]['date'] = $v['datetime'];   //第一行输出日期
                     $finally_array[$i]['month'] = $v['month'];  //第一行输出月份
                     $finally_array[$i]['total'] = number_format($v['total_money'],2);  //汇总记录结束
                     $total_month += $v['total_money'];
                     $total_sort += $v['total_money'];
                     $i++;
                 }



            }else{

                //生成一条记录
                if($last_sort){
                //生成上一条汇总记录
                 $finally_array[$i]['month'] =$last_month."汇总";
                 $finally_array[$i]['date'] = "";  //第一行输出日期
                 $finally_array[$i]['sort'] = "";  //第一行输出日期
                 $finally_array[$i]['class'] = 1;  //CSS控制器
                 $finally_array[$i]['total'] = number_format($total_month,2);  //汇总记录结束
                 $total_month = 0;  //月份汇总归零

                $i++;
                $finally_array[$i]['sort'] =$last_sort."汇总";
                $finally_array[$i]['date'] = "";  //第一行输出日期
                $finally_array[$i]['month'] ="";  //第一行输出月份
                $finally_array[$i]['total'] = number_format($total_sort,2);  //汇总记录结束
                $finally_array[$i]['class'] = 1;  //CSS控制器
                $total_all += $total_sort; //汇总总记录
                $total_sort = 0;//归零重计
                $i++;
                }
                //第一次进入循环
                $total_sort += $v['total_money'];
                $finally_array[$i]['sort'] = $v['sort'];  //第一行输出类别
                $finally_array[$i]['date'] = $v['datetime'];  //第一行输出日期
                $finally_array[$i]['month'] = $v['month'];  //第一行输出月份
                $finally_array[$i]['total'] = $v['total_money'];  //第一行输出价格
                $total_month += $v['total_money'];


            }

            //另起一页
            if ($k == $key_last){ //此为最后一次循环 生成汇总记录
                $i ++;  //插入新的汇总记录
                //  $total += $v['total'];
                $finally_array[$i]['sort'] = $v['sort'].'汇总';
                $finally_array[$i]['month'] ="";
                $finally_array[$i]['date'] = $v['date'];
                $finally_array[$i]['total'] = number_format($total_sort,2);  //汇总
                $finally_array[$i]['class'] = 1;  //CSS控制器
            }


            $i++; //增加


            $last_month = $v['month'];
            $last_sort = $v['sort'];
        }
        $finally_array[$i]['sort'] = '合计';
        $finally_array[$i]['class'] = 1;  //CSS控制器
        $finally_array[$i]['total'] = number_format($total_all,2);

        $this->assign('stus', $finally_array);
        $this->assign('page_title', "按时分类汇总");
        $this->assign('pageControl', $pageControl);
        $this->assign('begin_date', $begin_date);
        $this->assign('end_date', $end_date);
        $this->display();

    }

    //出库汇总
    public function chukutotal()
    {


        $stu_model = M('cklog');
        //导入分页助手类
        import('Org.Util.Page');

        //从账本中读取开始和结束时间
        $zhangben = M('zhangben');
        $_REQUEST['zhangben_id'] = isset($_REQUEST['zhangben_id']) ? $_REQUEST['zhangben_id'] : -1;
        if ($_REQUEST['zhangben_id'] != -1) {
            $zmap['id'] = $_REQUEST['zhangben_id'];
        }
        $zhangben_last = $zhangben->where($zmap)->order("id Desc")->find();
        $begin_date = $zhangben_last['begin_date'];
        $end_date = $zhangben_last['end_date'];   //账本日期
//获取开始结束日期
        $_REQUEST['begin_date'] = isset($_REQUEST['begin_date']) ? $_REQUEST['begin_date'] : $begin_date;
        $_REQUEST['end_date'] = isset($_REQUEST['end_date']) ? $_REQUEST['end_date'] : $end_date;
        //手动查询日期
        $map['datetime'] = array('between', $_REQUEST['begin_date'] . ',' . $_REQUEST['end_date']);
        $map['type'] = 2;
        $map['isbuy'] = array('neq', 1);
        $map['school_id'] =  $_SESSION['school_id'];
        $total = $stu_model
            ->where($map)
            ->order("sort ASC")
            ->count();
        $page_size = 20;  //流水账每页显示多少条以便打印
        $page = new Page($total, $page_size);
        $page->setConfig("header", '出库汇总');
        $pageControl = $page->show();

        $stus = $stu_model
            ->field('id,type,total_money,sort,datetime,month,menu,candj')
            ->where($map)
            ->order("month asc,datetime asc")
            //   ->limit($page->firstRow,$page->listRows)
            ->select();
        // echo $stu_model->getLastSql();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
//
        //定义处理后的数据
        $finally_array = array();
//上个月份
        $last_month = 0;
        $i = 0;
        //统计月总数金额
        $total_candj = 0;  //月单价数额
        $total_month = 0;   //月总数
        $j = 0;   //月内个数

        //统计所有时段总金额
        $total_all = 0;  //所有月总额之和
        $total_all_dj = 0; //所有月单价之和
        $s = 0;  //所有个数

        $key_last = count($stus) - 1;

        foreach ($stus as $k => $v) {


            $v['datetime'] = substr($v['datetime'], 0, 10);

            //月份是否相同
            if ($v['month'] == $last_month && $last_month != 0) {  //相同的话继续累加

                $total_month += $v['total_money'];
                $total_candj += $v['candj'];
                $j++;
                $s++;
                $finally_array[$i]['date'] = $v['datetime'];  //第一行输出日期
                $finally_array[$i]['menu'] = $v['menu'];  //菜单名称
                $finally_array[$i]['month'] = "";  //第一行输出月份
                $finally_array[$i]['total'] = $v['total_money'];  //第一行输出价格
                $finally_array[$i]['avg_candj'] = $v['candj'];  //第一行输出价格

            } else {  //月份不同的话

                  if ($last_month) {

                    //总数统计
                    $total_all += $total_month;
                    $total_all_dj += $total_candj;



                    //生成上一条汇总记录
                    $finally_array[$i]['month'] = $last_month . "汇总";
                    $finally_array[$i]['date'] = $j."天";  //第一行输出日期
                    $finally_array[$i]['class'] = 1;  //CSS控制器
                    $finally_array[$i]['total'] = number_format($total_month, 2);  //汇总记录结束
                    $finally_array[$i]['avg_candj'] =number_format($total_candj/$j, 2);  //汇总记录结束
                    $i++;
                      $j=0;
                      $total_month = 0;
                      $total_candj = 0;
                    //生成本次记录
                    $finally_array[$i]['month'] = $v['month'];
                    $finally_array[$i]['date'] = $v['datetime'];;  //第一行输出日期
                    $finally_array[$i]['menu'] = $v['menu'];  //菜单名称
                    $finally_array[$i]['class'] = 0;  //CSS控制器
                    $finally_array[$i]['total'] = $v['total_money'];
                    $finally_array[$i]['avg_candj'] =$v['candj'];  //汇总记录结束
                    $total_month += $v['total_money'];
                    $total_candj += $v['candj'];

                    $j++;
                    $s++;


                }else{
                    //第1次进入
                    //生成一条记录
                    //第一次进入循环
                    $total_month += $v['total_money'];
                    $total_candj += $v['candj'];
                    $finally_array[$i]['menu'] = $v['menu'];  //菜单名称
                    $finally_array[$i]['date'] = $v['datetime'];  //第一行输出日期
                    $finally_array[$i]['month'] = $v['month'];  //第一行输出月份
                    $finally_array[$i]['total'] = $v['total_money'];  //第一行输出价格
                    $finally_array[$i]['avg_candj'] = $v['candj'];  //第一行输出价格
                    $j++;
                    $s++;
                }

            }

            //另起一页
            if ($k == $key_last) { //此为最后一次循环 生成汇总记录
                $i++;  //插入新的汇总记录
                //  $total += $v['total'];
                $finally_array[$i]['month'] = $v['month'] . '汇总';
                $finally_array[$i]['date'] =$j."天";
                $finally_array[$i]['total'] = number_format($total_month,2);  //汇总
                $finally_array[$i]['avg_candj'] = number_format($total_candj / $j, 2);  //汇总
                $finally_array[$i]['class'] = 1;  //CSS控制器
                $total_all += $total_month;
                $total_all_dj += $total_candj;
            }

            //最后记录
            $i++; //增加
            $last_month = $v['month'];
        }
        $finally_array[$i]['month'] = '合计';
        $finally_array[$i]['total'] = number_format($total_all,2);
        $finally_array[$i]['date'] = $s."天";
        $finally_array[$i]['avg_candj'] = number_format($total_all_dj / $s,2);

        $this->assign('stus', $finally_array);
        $this->assign('page_title', "出库按时汇总");
        $this->assign('pageControl', $pageControl);
        $this->assign('begin_date', $begin_date);
        $this->assign('end_date', $end_date);
        $this->display();
    }


    //入库操作 ACTION
    public function update()
    {
        header("Content-Type:text/html;charset=utf-8");
        $kucun = M('kucun');
        $in_month = substr(trim($_POST['date']), 0, -3);
        if($_POST['total_money']<1){
            $this->error('总金额不能小于0！！');
        }

        //写日志
        $logdata=array(
            'type' => 1,
            'opuser' => $_SESSION['username'],
            'school_id' => $_SESSION['school_id'],
            'total_money' => $_POST['total_money'],
            'sort' => $_POST['sort'],
            'datetime' => $_POST['date'],
            'month' => $in_month,
            'menu' => $_POST['memo'],
            'memo'=>json_encode($_POST['detail'])
        );
        //结转处理
        if($_POST['memo']=='上期结转'){
            $logdata['isbuy'] = 1;
        }


        $log = M('cklog');
        $logid = $log->add($logdata);

        $common_field = array('school_id' => $_POST['school_id'], 'sort' => $_POST['sort'], 'date' => trim($_POST['date']),
            'month' => $in_month, 'type' => 1,'danjuhao'=>$_POST['danjuhao'],'shouhuoren'=>$_POST['shouhuoren'],'logid'=>$logid);
        foreach ($_POST['detail'] as $k=>$v){
            if($v['name']==''){
                continue;
            }
            if($v['mid'] && $v['mname']){
            $add_data_one=array('gid'=>$v['mid'],'name'=>$v['mname'],'guige'=>$v['guige'],'guige_unit'=>$v['guige_unit'],'unit'=>$v['unit_type'],'total'=>$v['zmoney'],'number'=>$v['number'],'memo'=>$_POST['memo']);
            }else{
            $return_data = $this->get_goods($v['name'],$v['unit_type']);
            $add_data_one=array('gid'=>$return_data['mid'],'name'=>$return_data['mname'],'guige'=>$v['guige'],'guige_unit'=>$v['guige_unit'],'unit'=>$v['unit_type'],'total'=>$v['zmoney'],'number'=>$v['number'],'memo'=>$_POST['memo']);
            }


            if(intval($v['guige'])>0){
                $add_data_one['price'] = $v['price']; //价格求平均
                $add_data_one['rest_number'] = $v['number'] * $v['guige'];
            }else {
                $add_data_one['price'] = $v['price'];
                $add_data_one['rest_number'] = $v['number'];
            }
            $add_data[] = $common_field + $add_data_one;
        }
        $insertInfo = $kucun->addAll($add_data);

            if ($insertInfo) {
                $this->success('添加成功！！');
            } else {
                $this->error('添加失败！！');
            }


        $this->redirect('rukudan?logid='.$logid);//重定向到控制器的方法  display是本控制的方法

    }

    function get_goods($name,$unit){
        $goods = M('goods');
        $goods_array=array(
            "school_id" => $_SESSION['school_id'],
            "name" => $name,
            "unit" => $unit,
            "pinyin"=>$this->pinyin1($name)
        );
        $mid = $goods->add($goods_array);
        return array('mid'=>$mid, 'mname' => $name);
    }

    public function showUpdate()
    {
        $stu = M('stu');
        $id = $_GET['id'];
        $stu_list = $stu->where("id=$id")->find();

        $teacher_class = M("teacher");
        $teacher_array = $teacher_class->select();
        $this->assign('teacher_array',$teacher_array);

        $this->assign('page_title', "修改");
        $this->assign('user_list', $stu_list);
        $this->display('update');
    }

    //入库入口
    public function showAdd()    {

        $this->assign('page_title', "入库");
  //供应商
        $company = M("company");
        $company_array = $company->where("school_id=".$_SESSION['school_id'])->select();
        $this->assign('company_array',$company_array);

        $stu = M('goods');
        $stu_list = $stu->where("school_id=".$_SESSION['school_id'])->select();
        $autodata = json_encode($stu_list);
        $this->assign('school_id', $_SESSION['school_id']);
        $this->assign('autodata', $autodata);
        $current_date = date('Y-m-d');
        $this->assign('current_date', $current_date);

        $djh = M("kucun");
        $danjuhao = $djh->field('danjuhao')
            ->where(array('type' => 1, "month" => substr($current_date, 0, 7),"school_id"=>$_SESSION['school_id'],'memo'=>array('neq','上期结转')))
            ->order('danjuhao desc')
            ->limit(1)
            ->find();
        $new_djh = intval($danjuhao['danjuhao']) + 1;
        $this->assign('danjuhao', $new_djh);

        $this->display('update');
    }
   //读取账本 AJAX
    public function ajax_zhangben()
    {
        $zbid = $_REQUEST['id'];
        $zhangben = M("zhangben");
        $zhangben_array = $zhangben->where("id=".$zbid)->find();
        echo json_encode($zhangben_array);
        exit();
    }



/**
 * @name: getfirstchar
 * @description: 获取汉子首字母
 * @param: string
 * @return: mixed
 * @author:
 * @create: 2014-09-17 21:46:52
**/
function getfirstchar($s0){
    $fchar = ord($s0{0});
    if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
    //$s1 = iconv("UTF-8","gb2312//IGNORE", $s0);
    // $s2 = iconv("gb2312","UTF-8//IGNORE", $s1);
    $s1 = $this->get_encoding($s0,'GB2312');
    $s2 = $this->get_encoding($s1,'UTF-8');
    if($s2 == $s0){$s = $s1;}else{$s = $s0;}
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if($asc >= -20319 and $asc <= -20284) return "A";
    if($asc >= -20283 and $asc <= -19776) return "B";
    if($asc >= -19775 and $asc <= -19219) return "C";
    if($asc >= -19218 and $asc <= -18711) return "D";
    if($asc >= -18710 and $asc <= -18527) return "E";
    if($asc >= -18526 and $asc <= -18240) return "F";
    if($asc >= -18239 and $asc <= -17923) return "G";
    if($asc >= -17922 and $asc <= -17418) return "H";
    if($asc >= -17417 and $asc <= -16475) return "J";
    if($asc >= -16474 and $asc <= -16213) return "K";
    if($asc >= -16212 and $asc <= -15641) return "L";
    if($asc >= -15640 and $asc <= -15166) return "M";
    if($asc >= -15165 and $asc <= -14923) return "N";
    if($asc >= -14922 and $asc <= -14915) return "O";
    if($asc >= -14914 and $asc <= -14631) return "P";
    if($asc >= -14630 and $asc <= -14150) return "Q";
    if($asc >= -14149 and $asc <= -14091) return "R";
    if($asc >= -14090 and $asc <= -13319) return "S";
    if($asc >= -13318 and $asc <= -12839) return "T";
    if($asc >= -12838 and $asc <= -12557) return "W";
    if($asc >= -12556 and $asc <= -11848) return "X";
    if($asc >= -11847 and $asc <= -11056) return "Y";
    if($asc >= -11055 and $asc <= -10247) return "Z";
    return null;
}
/**
 * @name: get_encoding
 * @description: 自动检测内容编码进行转换
 * @param: string data
 * @param: string to  目标编码
 * @return: string
**/
function get_encoding($data,$to){
	$encode_arr=array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');
	$encoded=mb_detect_encoding($data, $encode_arr);
	$data = mb_convert_encoding($data,$to,$encoded);
	return $data;
}

function pinyin1($zh){
    $ret = "";
    $s1 = iconv("UTF-8","gb2312", $zh);
    $s2 = iconv("gb2312","UTF-8", $s1);
    if($s2 == $zh){$zh = $s1;}
    for($i = 0; $i < strlen($zh); $i++){
        $s1 = substr($zh,$i,1);
        $p = ord($s1);
        if($p > 160){
            $s2 = substr($zh,$i++,2);
            $ret .= $this->getfirstchar($s2);
        }else{
            $ret .= $s1;
        }
    }
    return $ret;
}



}
?>




